<style lang="scss" scoped>
::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}

// ::v-deep input[type='number'] {
//   // -moz-appearance: textfield !important;
// }

.el-dialog-div {
  height: 50vh;
  overflow-x: hidden;
}

span.textname {
  display: -webkit-box;

  text-overflow: ellipsis;
  overflow: hidden;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  white-space: pre-wrap;
}

.el-input.is-disabled ::v-deep .el-input__inner {
  color: #606266;
  background-color: white;
  border: none;
}

.el-textarea.is-disabled ::v-deep .el-textarea__inner {
  color: #606266;
  background-color: white;
  border: none;
  width: 500px;
  resize: none;
  cursor: pointer;
}
</style>
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- <el-form-item label="select" prop="select">
        <el-input
          v-model="queryParams.select"
          placeholder="请输入select"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="from" prop="fromTable">
        <el-input
          v-model="queryParams.fromTable"
          placeholder="请输入from"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="左联" prop="leftAlliance">
        <el-input
          v-model="queryParams.leftAlliance"
          placeholder="请输入左联"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="条件" prop="where">
        <el-input
          v-model="queryParams.where"
          placeholder="请输入条件"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分组" prop="group">
        <el-input
          v-model="queryParams.group"
          placeholder="请输入分组"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排序" prop="sortOrder">
        <el-input
          v-model="queryParams.sortOrder"
          placeholder="请输入排序"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="limit" prop="limit">
        <el-input
          v-model="queryParams.limit"
          placeholder="请输入limit"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="预览sql" prop="previewSql">
        <el-input
          v-model="queryParams.previewSql"
          placeholder="请输入预览sql"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['conf:BiSqlFirstField:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['conf:BiSqlFirstField:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['conf:BiSqlFirstField:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['conf:BiSqlFirstField:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="mini"
          @click="handlebuildSelectSQLs"
          >批量生成SQL</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button plain size="mini" @click="handleSqlId">修改SqlId</el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="BiSqlFirstFieldList"
      @selection-change="handleSelectionChange"
      :height="600"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <!-- <el-table-column label="select" align="center" prop="select" />
      <el-table-column label="from" align="center" prop="fromTable" />
      <el-table-column label="左联" align="center" prop="leftAlliance" />
      <el-table-column label="条件" align="center" prop="where" />
      <el-table-column label="分组" align="center" prop="group" />
      <el-table-column label="排序" align="center" prop="sortOrder" />
      <el-table-column label="limit" align="center" prop="limit" /> -->
      <el-table-column label="来源表" align="center" prop="">
        <template v-slot="scope">
          <span
            style="
              color: rgb(37, 137, 255);
              cursor: pointer;
              text-decoration: underline;
              font-weight: bold;
            "
            @click="selectformisNew(scope.row, 10)"
            >来源表</span
          >
        </template></el-table-column
      >
      <el-table-column label="查询字段" align="center" prop="limit">
        <template slot-scope="scope">
          <span
            style="
              color: rgb(37, 137, 255);
              cursor: pointer;
              text-decoration: underline;
              font-weight: bold;
            "
            @click="selectformisNew(scope.row, 5)"
            >查询字段</span
          >
        </template></el-table-column
      >

      <el-table-column label="关联表" align="center" prop="">
        <template v-slot="scope">
          <span
            style="
              color: rgb(37, 137, 255);
              cursor: pointer;
              text-decoration: underline;
              font-weight: bold;
            "
            @click="selectformisNew(scope.row, 20)"
            >关联表</span
          >
        </template></el-table-column
      >
      <el-table-column label="筛选条件" align="center" prop="">
        <template v-slot="scope">
          <span
            style="
              color: rgb(37, 137, 255);
              cursor: pointer;
              text-decoration: underline;
              font-weight: bold;
            "
            @click="selectformisNew(scope.row, 30)"
            >筛选条件</span
          >
        </template></el-table-column
      >
      <el-table-column label="分组字段" align="center" prop="">
        <template v-slot="scope">
          <span
            style="
              color: rgb(37, 137, 255);
              cursor: pointer;
              text-decoration: underline;
              font-weight: bold;
            "
            @click="selectformisNew(scope.row, 40)"
            >分组字段</span
          >
        </template></el-table-column
      >
      <el-table-column label="结果筛选" align="center" prop="">
        <template v-slot="scope">
          <span
            style="
              color: rgb(37, 137, 255);
              cursor: pointer;
              text-decoration: underline;
              font-weight: bold;
            "
            @click="selectformisNew(scope.row, 50)"
            >结果筛选</span
          >
        </template></el-table-column
      >
      <el-table-column label="排序" align="center" prop="">
        <template v-slot="scope">
          <span
            style="
              color: rgb(37, 137, 255);
              cursor: pointer;
              text-decoration: underline;
              font-weight: bold;
            "
            @click="selectformisNew(scope.row, 60)"
            >排序</span
          >
        </template></el-table-column
      >
      <el-table-column label="对话生成sql" align="center" prop="">
        <template v-slot="scope">
          <span
            style="
              color: rgb(37, 137, 255);
              cursor: pointer;
              text-decoration: underline;
              font-weight: bold;
            "
            @click="handleVisible(scope.row)"
            >对话生成sql</span
          >
        </template></el-table-column
      >
      <el-table-column label="预览" align="center" prop="">
        <template v-slot="scope">
          <span
            style="
              color: rgb(37, 137, 255);
              cursor: pointer;
              text-decoration: underline;
              font-weight: bold;
            "
            @click="selectAfter(scope.row)"
            >预览</span
          >
        </template></el-table-column
      >
      <el-table-column width="250" label="预览sql" align="center" prop="">
        <template slot-scope="scope">
          <mypopover :popoverInput="scope.row.previewSql" />
        </template>
      </el-table-column>
      <el-table-column label="去重关键字" align="center" prop="distinctKeyWord">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.distinctKeyWord"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="说明" align="center" prop="description" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['conf:BiSqlFirstField:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['conf:BiSqlFirstField:remove']"
            >删除</el-button
          >
        </template></el-table-column
      >
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog
      title="对话生成sql结果"
      :visible.sync="openmsg"
      width="50%"
      append-to-body
      v-if="openmsg"
    >
      <div class="el-dialog-div">
        <!-- {{  }} -->
        <el-input
          v-model="msg"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 200 }"
          :style="{ width: '100%' }"
          @change="changeinput"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMsg">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="tagkeyVisible"
      width="700px"
      append-to-body
      v-if="tagkeyVisible"
    >
      <div class="el-dialog-div">
        <el-form
          ref="form"
          :model="formData"
          label-position="top"
          :inline="true"
        >
          <!-- :style="{ width: '100%' }" -->
          <!-- <el-row> -->
          <el-form-item label="对话框" prop="input">
            <el-input
              v-model="input"
              placeholder="请输入内容"
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 12 }"
              style="display: block"
            />
          </el-form-item>
          <!-- </el-row> -->
          <el-form-item
            v-for="(item, index) in formData.libraryIdList"
            :key="index"
          >
            <el-select
              style="width: 200px"
              v-model="item.tableName"
              clearable
              filterable
              remote
              :remote-method="getDatacomment"
              placeholder="请输入表描述"
              allow-create
              @change="changetableName"
            >
              <el-option
                v-for="item in options"
                :key="item.tableName"
                :label="`${item.comment}`"
                :value="item.tableName"
              >
              </el-option>
            </el-select>
            <el-select
              style="width: 250px"
              v-model="item.tableName"
              clearable
              filterable
              remote
              :remote-method="gettableName"
              placeholder="数据库表名"
              allow-create
              @change="changetableName"
            >
              <el-option
                v-for="item in options"
                :key="item.tableName"
                :label="`${item.tableName}`"
                :value="item.tableName"
              >
              </el-option>
            </el-select>
            <!-- <el-input
              :disabled="true"
              style="width: 150px"
              v-model="item.comment"
              placeholder="请输入字段名"
            ></el-input>
          
            <el-input
              style="width: 150px"
              v-model="item.value"
              placeholder="请输入字段值"
            ></el-input> -->
            <!-- <span v-if="item.is_nullable == 'NO'">(必填)</span> -->
            <span v-if="formData.libraryIdList.length > 0">
              <el-button type="primary" size="mini" @click="addLibraryIdList"
                >新增</el-button
              >
              <el-button type="danger" size="mini" @click="delRow(item, index)"
                >删除</el-button
              >
            </span>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormData">确 定</el-button>
        <!-- <el-button @click="cancel">取 消</el-button> -->
      </div>
    </el-dialog>

    <!-- 添加或修改查询命令一级对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="select" prop="select">
          <el-input v-model="form.select" placeholder="请输入select" />
        </el-form-item>
        <el-form-item label="from" prop="fromTable">
          <el-input v-model="form.fromTable" placeholder="请输入from" />
        </el-form-item>
        <el-form-item label="左联" prop="leftAlliance">
          <el-input v-model="form.leftAlliance" placeholder="请输入左联" />
        </el-form-item>
        <el-form-item label="条件" prop="where">
          <el-input v-model="form.where" placeholder="请输入条件" />
        </el-form-item>
        <el-form-item label="分组" prop="group">
          <el-input v-model="form.group" placeholder="请输入分组" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input v-model="form.sortOrder" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="limit" prop="limit">
          <el-input v-model="form.limit" placeholder="请输入limit" />
        </el-form-item> -->
        <el-form-item label="预览sql" prop="previewSql">
          <el-input
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 12 }"
            v-model="form.previewSql"
            placeholder="请输入预览sql"
          />
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input v-model="form.description" placeholder="请输入说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <BiSqlWhereRelationship :id="id" v-show="panelType == 30" />
    <component :is="currentComponent" :id="id"></component>
    <!-- <BiSqlSelectField :id="id" /> -->
    <el-dialog
      append-to-body
      :visible.sync="openAfter"
      width="1800px"
      v-if="openAfter"
    >
      <After :id="id" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listBiSqlFirstField,
  getBiSqlFirstField,
  delBiSqlFirstField,
  addBiSqlFirstField,
  updateBiSqlFirstField,
  buildSelectSQLs,
} from "@/api/conf/BiSqlFirstField";
import BiSqlSelectField from "@/views/conf/sql/BiSqlSelectField/index.vue";
import BiSqlFromTable from "@/views/conf/sql/BiSqlFromTable/index.vue";
import BiSqlJoinTable from "@/views/conf/sql/BiSqlJoinTable/index.vue";
import BiSqlWhereDwd from "@/views/conf/sql/BiSqlWhereDwd/index.vue";
import BiSqlGroupField from "@/views/conf/sql/BiSqlGroupField/index.vue";
import BiSqlHavingDwd from "@/views/conf/sql/BiSqlHavingDwd/index.vue";
// import BiSqlGroupField from "@/views/conf/sql/BiSqlGroupField/index.vue";
import BiSqlOrderField from "@/views/conf/sql/BiSqlOrderField/index.vue";
import BiSqlWhereRelationship from "@/views/conf/sql/BiSqlWhereRelationship/index.vue";
import { selectTableNameList, getSqlFromGpt } from "@/api/conf/SysTableField";
import After from "./After.vue";
export default {
  name: "BiSqlFirstField",
  props: {
    row: {
      type: Object,
      default: () => {},
    },
  },
  components: {
    BiSqlSelectField,
    BiSqlFromTable,
    BiSqlJoinTable,
    BiSqlWhereDwd,
    BiSqlGroupField,
    BiSqlHavingDwd,
    BiSqlOrderField,
    BiSqlWhereRelationship,
    After,
  },
  data() {
    return {
      msg: "",
      openmsg: false,
      input: "",

      options: [],
      formData: {
        libraryIdList: [{ tableName: "" }],
      },
      tagkeyVisible: false,

      openAfter: false,
      id: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 查询命令一级表格数据
      BiSqlFirstFieldList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        select: null,
        fromTable: null,
        leftAlliance: null,
        where: null,
        group: null,
        sortOrder: null,
        limit: null,
        previewSql: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      panelType: 10,
    };
  },
  created() {
    this.getList();
  },
  watch: {
    row: {
      handler: function (newnew, oldold) {
        console.log("newnew", newnew);
        if (newnew) {
          this.queryParams.id = this.row.sqlId;
          this.queryParams.pageSize = 1000;
          this.getList();
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    // ...mapGetters(["userId"]),
    currentComponent() {
      let type = parseInt(this.panelType);
      switch (type) {
        case 5:
          return "BiSqlSelectField";
        case 10:
          return "BiSqlFromTable";
        case 20:
          return "BiSqlJoinTable";
        case 30:
          return "BiSqlWhereDwd";
        case 40:
          return "BiSqlGroupField";
        case 50:
          return "BiSqlHavingDwd";
        case 60:
          return "BiSqlOrderField";

        default:
          return "";
      }
    },
  },
  methods: {
    changeinput() {
      this.$forceUpdate();
    },
    handleVisible(row) {
      this.id = row.id;
      this.tagkeyVisible = true;
    },
    // 打开加载层
    openLoading() {
      this.$modal.loading("正在加载，请稍候！");
    },
    submitFormData() {
      if (!this.input) {
        this.$modal.msgError("请输入对话框内容");
        return;
      }
      if (!this.formData.libraryIdList[0].tableName) {
        this.$modal.msgError("请选择表");
        return;
      }
      let obj = {
        input: this.input,
        tableNameList: this.formData.libraryIdList.map(
          (item) => item.tableName
        ),
      };
      this.openLoading();
      getSqlFromGpt(obj).then((response) => {
        this.$modal.closeLoading();
        this.msg = response;
        this.openmsg = true;
      });
    },
    changetableName(value) {
      const selectedOption = this.options.find(
        (option) => option.tableName === value
      );
      console.log(JSON.stringify(selectedOption)); // 这里就是整个选项对象
      this.form.tableComment = selectedOption.comment;
    },
    getDatacomment(key) {
      selectTableNameList({ comment: key }).then((response) => {
        this.options = response;
      });
    },
    gettableName(key) {
      selectTableNameList({ tableName: key }).then((response) => {
        this.options = response;
      });
    },
    //添加库存名称
    addLibraryIdList() {
      this.formData.libraryIdList.push({
        comment: "",
        field_name: "",
        value: "",
      });
    },
    //库存名称删除
    delRow(item, index) {
      if (this.formData.libraryIdList.length > 1) {
        this.formData.libraryIdList.splice(index, 1);
      } else {
        this.$message.warning("至少选择一项");
      }
    },
    handleSqlId() {
      // if (!this.queryParams.sqlId) {
      //   this.$modal.msgError("这个按钮是对外的");
      //   return;
      // }
      if (this.ids.length != 1) {
        this.$modal.msgError("请只选择一条数据");
        return;
      } else {
        this.$emit("handleSqlId", this.ids[0]);
      }
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.distinctKeyWord === "0" ? "不去重" : "去重";
      this.$modal
        .confirm('确认要"' + text + '"关键字吗？')
        .then(function () {
          return updateBiSqlFirstField(row);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.distinctKeyWord = row.distinctKeyWord === "0" ? "1" : "0";
        });
    },
    handlebuildSelectSQLs() {
      console.log(JSON.stringify(this.ids));
      if (this.ids.length < 1) {
        this.$modal.msgError("请至少选择一条数据");
        return;
      }
      buildSelectSQLs(this.ids).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess("生成成功");
          this.getList();
        }
      });
    },
    // tableEdit(row, column, cell, event) {
    //   this.id = row.id;
    // },
    selectAfter(row) {
      this.id = row.id;
      this.openAfter = true;
    },
    selectformisNew(row, panelType) {
      this.panelType = panelType;
      this.id = row.id;
    },
    handleGo(path) {
      this.$router.push({
        path: path,
        // query: { tableName: this.queryParams.tableName },
      });
    },
    /** 查询查询命令一级列表 */
    getList() {
      this.loading = true;
      listBiSqlFirstField(this.queryParams).then((response) => {
        this.BiSqlFirstFieldList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        select: null,
        fromTable: null,
        leftAlliance: null,
        where: null,
        group: null,
        sortOrder: null,
        limit: null,
        previewSql: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.id = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加查询命令一级";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBiSqlFirstField(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改查询命令一级";
      });
    },
    submitMsg() {
      this.form.id = this.id;
      this.form.previewSql = this.msg;
      delete this.form.tableComment;
      this.openmsg = false;
      this.submitForm();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBiSqlFirstField(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBiSqlFirstField(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除查询命令一级编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBiSqlFirstField(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "conf/BiSqlFirstField/export",
        {
          ...this.queryParams,
        },
        `BiSqlFirstField_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
